

import { Singleton } from "../../meshTools/Singleton";
import { EventType } from "../common/EventCenter";
import { GameMgr } from "../common/GameMgr";
import { ReceivedMessageBean, SendMessageBean } from "./MessageBaseBean";
import { MessageId } from "./MessageId";
import { WebSocketTool, WebSocketToolState } from "./WebSocketTool";

export class WebSocketManager extends Singleton {

    
    webState: WebSocketToolState = WebSocketToolState.Closing;
    //连接 socket
    connect() {
        WebSocketTool.GetInstance().setSocketFunction(this.msgData, this.socketState);
        WebSocketTool.GetInstance().connect();//连接长链接
    }

    //这个是用来接收服务器返回回来的数据
    private msgData(msg: string) {
        const parsedData = JSON.parse(msg) as ReceivedMessageBean;
        if (parsedData.code == 0) {//正常数据
            GameMgr.Event.Send(EventType.ReceiveMessage, parsedData);//将收到的消息发送出去
        } else {
            GameMgr.Event.Send(EventType.ReceiveErrorMessage, parsedData);//将收到的消息发送出去
        }
    }

    //这个是接收 websocket 状态的
    private socketState(webState: WebSocketToolState) {
        GameMgr.Console.Log('webSocket状态' + webState);
        WebSocketManager.GetInstance().webState = webState;
    }


    //发送消息  data 请求参数 是个对象{}
    sendMsg(msgId: MessageId, data: any) {

        let sendMessageBean: SendMessageBean = {
            msgId: msgId,
            data: data,
        };
        const jsonString = JSON.stringify(sendMessageBean);

        WebSocketTool.GetInstance().send(jsonString);
    }


}